# -*- coding: utf-8 -*-
import win32gui
import win32con
import win32api
from datetime import datetime
from PIL import ImageGrab
from PIL import Image
import time
import random

def main():
    color_list = {  # 颜色对应的RGB值
        u'紫': (164, 130, 209),
        u'蓝': (91,  196, 241),
        u'黄': (255, 228,  85),
        u'白': (255, 255, 255),
        u'红': (255,  86, 110),
        u'绿': (201, 255, 103),
        u'橙': (241, 171,  98),}

    offset = {u'左': (-1, 0), u'右': (1, 0), u'上': (0, -1), u'下': (0, 1)}

    offset_test = [
        ((-2, 0), (-1, 0), (0, 0)),
        ((-1, 0), (0, 0), (1, 0)),
        ((0, 0), (1, 0), (2, 0)),
        ((0, -2), (0, -1), (0, 0)),
        ((0, -1), (0, 0), (0, 1)),
        ((0, 0), (0, 1), (0, 2)),]

    w, h = 7, 7  # 地图的长和宽
    size = 57  # 每个头像的大小
    dx, dy = 26, 20  # 取颜色和左上角的偏移
    left, top = 7, 246  # 地图和截图的便宜
    m = [[u'空'] * w for i in xrange(h)]  # 地图 w x h

    # 计算
    def run(flag):
        # 截取游戏画面
        hwnd = win32gui.FindWindow(0, u'夜神安卓模拟器')
        if hwnd:
            win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
            win32gui.SetForegroundWindow(hwnd)
            rect = win32gui.GetWindowRect(hwnd)
            im = ImageGrab.grab(rect)
            # filename = '.'.join([datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f'), 'png'])
            # im.save(filename, 'png')
        else:
            rect = (0, 0, 0, 0)
            im = Image.open('2016_10_04_13_37_23_531000.png')

        # 刷新地图
        for y in xrange(0, h):
            for x in xrange(0, w):
                xx, yy = left + x * size + dx, top + y * size + dy
                for e in color_list:
                    if sum([abs(a - b) for a, b in zip(im.getpixel((xx, yy)), color_list[e])]) < 15:
                        m[y][x] = e
                        break
                else:
                    m[y][x] = u'空'

        # 打印
        if False:
            print u'====================='
            for y in xrange(0, h):
                for x in xrange(0, w):
                    print m[y][x],
                else:
                    print


        if flag:
            ylist = range(0, h)
            xlist = range(0, w)
        else:
            ylist = range(h - 1, -1, -1)
            xlist = range(w - 1, -1, -1)

        # 找是否可以消
        for y in ylist:
            for x in xlist:
                for e in offset:
                    xx, yy = x + offset[e][0], y + offset[e][1]
                    if not (0 <= xx < w and 0 <= yy < h):
                        continue
                    # 交换
                    m[y][x], m[yy][xx] = m[yy][xx], m[y][x]

                    # 判断交换后是否可以消
                    for k in offset_test:
                        x1 = xx + k[0][0]
                        y1 = yy + k[0][1]
                        x2 = xx + k[1][0]
                        y2 = yy + k[1][1]
                        x3 = xx + k[2][0]
                        y3 = yy + k[2][1]

                        if not (0 <= x1 < w and 0 <= y1 < h
                            and 0 <= x2 < w and 0 <= y2 < h
                            and 0 <= x3 < w and 0 <= y3 < h):
                            continue
                        if m[y1][x1] == m[y2][x2] == m[y3][x3] != u'空':
                            pos = (rect[0] + left + x * size + dx + random.randint(-15, 15), rect[1] + top + y * size + dy + random.randint(-15, 15))
                            win32api.SetCursorPos(pos)
                            win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN ,0,0,0,0)
                            time.sleep(random.random() / 50)
                            win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
                            time.sleep(random.random() / 20)

                            pos = (rect[0] + left + xx * size + dx + random.randint(-15, 15), rect[1] + top + yy * size + dy + random.randint(-15, 15))
                            win32api.SetCursorPos(pos)
                            win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
                            time.sleep(random.random() / 50)
                            win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
                            return

                    # 交换
                    m[y][x], m[yy][xx] = m[yy][xx], m[y][x]

    cout = 0
    flag = True
    while cout < 60:
        run(flag)
        time.sleep(0.5 + random.random())
        flag = not flag
        cout += 1
        print cout

if __name__ == '__main__':
    main()
